const { ipcMain, BrowserWindow } = require('electron')

const getSource = (url) => {
    return new Promise((resolve, reject) => {
        const win = new BrowserWindow({
            width: 1920,
            height: 1080,
            show: false,
            webPreferences: {
                offscreen: true
            }
        })

        win.loadURL(url)

        win.webContents.on('did-finish-load', () => {
            setTimeout(async () => {
                const title = win.getTitle()
                try {
                    const image = await win.webContents.capturePage()
                    if (image.isEmpty()) {
                        resolve({ screenshot: null, message: `无法访问「${url}」，请检查域名地址` })
                    } else {
                        const screenshot = image.toDataURL()
                        resolve({ title, screenshot, url, favorite: false, hover: false, active: false, isDelete: false })
                    }
                } catch (error) {
                    reject(error)
                }
            }, 2000);

        })

    })

}

ipcMain.handle('on-url-event', async (e, url) => {
    return await getSource(url)
})

